<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.keyword"
        placeholder="商品名称/编码"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select v-model="listQuery.category" placeholder="商品分类" clearable style="width: 120px" class="filter-item">
        <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-model="listQuery.stockStatus" placeholder="库存状态" clearable style="width: 120px" class="filter-item">
        <el-option label="库存充足" value="normal" />
        <el-option label="库存不足" value="low" />
        <el-option label="库存告急" value="critical" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreateProductMain">
        添加商品
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="95">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="商品名称">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="商品编码" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.code }}
        </template>
      </el-table-column>
      <el-table-column label="分类" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.category }}
        </template>
      </el-table-column>
      <el-table-column label="当前库存" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.stock }}
        </template>
      </el-table-column>
      <el-table-column label="库存状态" width="110" align="center">
        <template slot-scope="scope">
          <el-tag :type="getStockStatusType(scope.row.stockStatus)">
            {{ getStockStatusText(scope.row.stockStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleInStock(row)">
            入库
          </el-button>
          <el-button type="warning" size="mini" @click="handleOutStock(row)">
            出库
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <!-- 入库操作表单 -->
        <template v-if="dialogType === 'in'">
          <el-form-item label="ID" prop="id">
            <el-input v-model="temp.id" placeholder="请输入入库记录ID" />
          </el-form-item>
          <el-form-item label="商品" prop="productId">
            <el-select v-model="temp.productId" placeholder="请选择商品" @change="handleProductChange">
              <el-option
                v-for="item in productOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <el-button type="text" @click="handleCreateProduct">创建新商品</el-button>
          </el-form-item>
          <!-- 显示选定商品的名称和ID -->
          <el-form-item label="选定商品" v-if="dialogType === 'in' && temp.productId">
            <span>ID: {{ temp.productId }}</span>
            <el-divider direction="vertical"></el-divider>
            <span>名称: {{ temp.name }}</span>
          </el-form-item>
          <el-form-item label="当前库存">
            <span>{{ temp.stock }}</span>
          </el-form-item>
          <el-form-item label="操作类型">
            <span>{{ dialogType === 'in' ? '入库' : '出库' }}</span>
          </el-form-item>
          <el-form-item label="数量" prop="quantity">
            <el-input-number v-model="temp.quantity" :min="1" :max="dialogType === 'out' ? temp.stock : 9999" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="temp.remark" type="textarea" :rows="2" />
          </el-form-item>
        </template>
        <!-- 出库操作表单 (Keep this part for 'out' type) -->
        <template v-else>
          <el-form-item label="商品名称">
            <span>{{ temp.name }}</span>
            <el-button type="text" @click="handleCreateProduct">创建新商品</el-button>
          </el-form-item>
          <el-form-item label="当前库存">
            <span>{{ temp.stock }}</span>
          </el-form-item>
          <el-form-item label="操作类型">
            <span>{{ dialogType === 'in' ? '入库' : '出库' }}</span>
          </el-form-item>
          <el-form-item label="数量" prop="quantity">
            <el-input-number v-model="temp.quantity" :min="1" :max="dialogType === 'out' ? temp.stock : 9999" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="temp.remark" type="textarea" :rows="2" />
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="handleSubmit">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="创建商品" :visible.sync="createProductDialogVisible">
      <el-form
        ref="createProductForm"
        :rules="createProductRules"
        :model="newProductTemp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="ID" prop="id">
          <el-input v-model="newProductTemp.id" />
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="newProductTemp.name" />
        </el-form-item>
        <el-form-item label="商品编码" prop="code">
          <el-input v-model="newProductTemp.code" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="newProductTemp.category" class="filter-item" placeholder="请选择分类">
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="newProductTemp.price" :precision="2" :step="0.1" :min="0" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="newProductTemp.stock" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="newProductTemp.status" class="filter-item" placeholder="请选择">
            <el-option label="在售" value="在售" />
            <el-option label="下架" value="下架" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="createProductDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCreateProduct">确认创建</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getInventoryList, addInventoryIn, addInventoryOut } from '@/api/inventory'
import { getCategories } from '@/api/products/category'
import { getProductList, addProduct } from '@/api/products'
import Pagination from '@/components/Pagination'

export default {
  name: 'InventoryList',
  components: { Pagination },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        keyword: undefined,
        category: undefined,
        stockStatus: undefined
      },
      categoryOptions: [],
      productOptions: [],
      temp: {
        id: undefined,
        productId: undefined,
        name: '',
        stock: 0,
        quantity: 1,
        remark: ''
      },
      dialogFormVisible: false,
      dialogType: 'in',
      dialogTitle: '',
      rules: {
        id: [{ required: true, message: '请输入入库记录ID', trigger: 'blur' }],
        productId: [{ required: true, message: '请选择商品', trigger: 'change' }],
        quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }]
      },
      createProductDialogVisible: false,
      newProductTemp: {
        id: undefined,
        name: '',
        code: '',
        category: '',
        price: 0,
        stock: 0,
        status: '在售'
      },
      createProductRules: {
        id: [{ required: true, message: '请输入商品ID', trigger: 'blur' }],
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        code: [{ required: true, message: '请输入商品编码', trigger: 'blur' }],
        category: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
        price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        stock: [{ required: true, message: '请输入商品库存', trigger: 'blur' }],
        status: [{ required: true, message: '请选择商品状态', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
    this.getCategoryOptions()
    this.getProductOptions()
  },
  methods: {
    async getList() {
      this.listLoading = true
      try {
        const { data } = await getInventoryList(this.listQuery)
        this.list = data.items.map(item => ({
          ...item,
          name: item.productName || item.name,
          code: item.productCode || item.code,
          stockStatus: item.stock > 50 ? 'normal' : item.stock > 10 ? 'low' : 'critical'
        }))
        this.total = data.total
      } finally {
        this.listLoading = false
      }
    },
    async getCategoryOptions() {
      try {
        const { data } = await getCategories()
        console.log('Fetched categories data:', data);
        if (Array.isArray(data)) {
          this.categoryOptions = data.map(item => ({
            label: item.name,
            value: item.name
          }))
          console.log('Formatted category options:', this.categoryOptions);
        } else {
          console.error('getCategories did not return an array:', data);
          this.categoryOptions = [];
        }
      } catch (error) {
        console.error('获取分类失败:', error)
        this.categoryOptions = []
      }
    },
    async getProductOptions() {
      try {
        const response = await getProductList();
        console.log('Fetched product list response:', response);
        const data = response.data;
        console.log('Fetched product list data (raw):', data);
        
        if (data && Array.isArray(data.items)) {
          this.productOptions = data.items.map(item => ({
            ...item,
            stockStatus: item.stock > 50 ? 'normal' : item.stock > 10 ? 'low' : 'critical'
          }))
          console.log('Formatted product options for dropdown:', this.productOptions)
        } else {
          console.error('getProductList did not return expected format:', data);
          this.productOptions = [];
        }
      } catch (error) {
        console.error('获取商品列表失败:', error)
        this.productOptions = []
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    getStockStatusType(status) {
      const statusMap = {
        normal: 'success',
        low: 'warning',
        critical: 'danger'
      }
      return statusMap[status]
    },
    getStockStatusText(status) {
      const statusMap = {
        normal: '库存充足',
        low: '库存不足',
        critical: '库存告急'
      }
      return statusMap[status]
    },
    handleProductChange(productId) {
      console.log('选择的商品ID:', productId)
      const product = this.productOptions.find(p => p.id === productId)
      console.log('找到的商品:', product)
      if (product) {
        this.temp = {
          ...this.temp,
          id: product.id,
          productId: product.id,
          name: product.name,
          code: product.code,
          stock: product.stock || 0,
          category: product.category
        }
      }
    },
    handleInStock() {
      console.log('Opening In Stock dialog');
      this.temp = {
        id: undefined,
        productId: undefined,
        name: '',
        code: '',
        stock: 0,
        quantity: 1,
        remark: '',
        category: ''
      }
      this.dialogType = 'in'
      this.dialogTitle = '商品入库'
      this.dialogFormVisible = true
      if (this.productOptions.length === 0) {
        this.getProductOptions()
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleOutStock(row) {
      this.temp = {
        ...row,
        quantity: 1,
        remark: ''
      }
      this.dialogType = 'out'
      this.dialogTitle = '商品出库'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleSubmit() {
      this.$refs['dataForm'].validate(async (valid) => {
        if (valid) {
          try {
            if (this.dialogType === 'in') {
              await addInventoryIn({
                id: this.temp.id,
                productId: this.temp.productId,
                productName: this.temp.name,
                productCode: this.temp.code,
                quantity: this.temp.quantity,
                remark: this.temp.remark
              })
              const product = this.list.find(p => p.id === this.temp.productId)
              if (product) {
                product.stock += this.temp.quantity
                product.stockStatus = product.stock > 50 ? 'normal' : product.stock > 10 ? 'low' : 'critical'
              }
            } else {
              await addInventoryOut({
                productId: this.temp.id,
                quantity: this.temp.quantity,
                remark: this.temp.remark
              })
              const product = this.list.find(p => p.id === this.temp.id)
              if (product) {
                product.stock -= this.temp.quantity
                product.stockStatus = product.stock > 50 ? 'normal' : product.stock > 10 ? 'low' : 'critical'
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: this.dialogType === 'in' ? '入库成功' : '出库成功',
              type: 'success',
              duration: 2000
            })
          } catch (error) {
            console.error(this.dialogType === 'in' ? '入库失败:' : '出库失败:', error)
            this.$message.error(this.dialogType === 'in' ? '入库失败' : '出库失败')
          }
        }
      })
    },
    handleCreateProductMain() {
      this.handleCreateProduct()
    },
    handleCreateProduct() {
      this.createProductDialogVisible = true
      this.newProductTemp = {
        id: undefined,
        name: '',
        code: '',
        category: '',
        price: 0,
        stock: 0,
        status: '在售'
      }
      this.getCategoryOptions()
      this.$nextTick(() => {
        this.$refs['createProductForm'].clearValidate()
      })
    },
    async submitCreateProduct() {
      this.$refs['createProductForm'].validate(async (valid) => {
        if (valid) {
          if (this.productOptions.some(item => String(item.id) === String(this.newProductTemp.id))) {
            this.$message.warning('该商品ID已存在，请勿重复创建')
            return
          }
          if (this.productOptions.some(item => item.name === this.newProductTemp.name)) {
            this.$message.warning('该商品名称已存在，请勿重复创建')
            return
          }
          try {
            await addProduct(this.newProductTemp)
            this.$notify({
              title: '成功',
              message: '商品创建成功',
              type: 'success',
              duration: 2000
            })
            this.createProductDialogVisible = false
            this.getProductOptions()
            this.getList()
          } catch (error) {
            console.error('商品创建失败:', error)
            this.$message.error('商品创建失败')
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .filter-container {
    padding-bottom: 10px;
    .filter-item {
      display: inline-block;
      vertical-align: middle;
      margin-bottom: 10px;
      margin-right: 10px;
    }
  }
}
</style> 